﻿using System;
using Common.Entities;
using Common.Exceptions;
using Common.Utils.Constants;
using DataAccess.Accessors.Interfaces;
using DataAccess.Converters;
using DataAccess.Repository.Interfaces;

namespace DataAccess.Repository
{
    public class UserRepository : IUserRepository
    {
        private readonly IUserAccessor _userAccessor;
        private readonly IUserEntityConverter _userEntityConverter;
        private readonly IUserAccountRepository _userAccountRepository;

        public UserRepository(IUserAccessor userAccessor, IUserEntityConverter userEntityConverter, IUserAccountRepository userAccountRepository)
        {
            _userAccessor = userAccessor;
            _userEntityConverter = userEntityConverter;
            _userAccountRepository = userAccountRepository;
        }

        public User GetUserByUsernameAndPassword(string userName, string password)
        {
            try
            {
                var userDao = _userAccessor.GetUser(userName, password);
                return userDao != null ? _userEntityConverter.ConvertToEntity(userDao) : null;
            }
            catch (Exception innerException)
            {
                throw new DataAccessException(ExceptionMessage.DataAccessException, innerException);
            }
        }

        public bool UserExists(string userName)
        {
            try
            {
                var userDao = _userAccessor.GetUser(userName);
                return userDao != null;
            }
            catch (Exception innerException)
            {
                throw new DataAccessException(ExceptionMessage.DataAccessException, innerException);
            }
        }

        public void Save(User user)
        {
            var userDao = _userEntityConverter.ConvertToEntityDAO(user);
            try
            {
                _userAccessor.SaveNewUser(userDao);
            }
            catch (Exception innerException)
            {
                throw new DataAccessException(ExceptionMessage.DataAccessException, innerException);
            }

            if(!user.UserAccounts.IsNullOrEmpty())
            {
                try
                {
                    _userAccountRepository.SaveUserAccounts(userDao.UserId, user.UserAccounts);
                }
                catch (Exception innerException)
                {
                    throw new DataAccessException(ExceptionMessage.DataAccessException, innerException);
                }
            }
        }
    }
}
